package ac.rfr.manager;

import java.io.File;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import javax.swing.JFileChooser;

import ac.notification.event.INotificationListenerLite;
import ac.notification.event.NotificationEvent;
import ac.notification.manager.NotificationRegistrarLite;
import ac.notification.manager.NotificationWarehouse;
import ac.rfr.store.Dictionary;
import ac.rfr.store.IIdentifiers;
import ac.rfr.ui.TemplatePreviewDialog;

public class TemplateManager implements INotificationListenerLite,IIdentifiers {


	private NotificationWarehouse notificationWarehouse;
	private TemplatePreviewDialog previewDialog;

	public TemplateManager()
	{
		notificationWarehouse = NotificationWarehouse.getNotificationWarehouse();
		previewDialog = new TemplatePreviewDialog();
		NotificationRegistrarLite.registerListener(this);
	}


	@Override
	public Set<String> declaredSubscriptionSet() {
		Set<String> subscriptionSet = new HashSet<String>();
		subscriptionSet.add(CMD_OPEN_TEMPLATE);
		return subscriptionSet;
	}

	@Override
	public void receiveEvent(String notificationId) {
		NotificationEvent ne = notificationWarehouse.getNotificationEvent(notificationId);
		if(null != ne)
		{
			if(ne.getPropertyIdentifier().contains(CMD_OPEN_TEMPLATE))
			{
				openTemplateFile();
			}
		}else{
			System.err.println("No notification event exists for notification: " + notificationId);			
		}
	}


	private void openTemplateFile() {
		Runnable openTask = new Runnable() {
			@Override
			public void run() {
				JFileChooser fileChooser = new JFileChooser();
				fileChooser.setDialogTitle("Open Template File");
				fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
				fileChooser.setMultiSelectionEnabled(false);
				int selectedOption = fileChooser.showOpenDialog(null);
				if(JFileChooser.APPROVE_OPTION == selectedOption)
				{
					File file = fileChooser.getSelectedFile();
					try {
						Dictionary.currentTemplate.load(new FileReader(file));
						Set<Object> headers = new TreeSet<Object>();
						
						headers.add("Field Name");
						headers.add("Field Length[Bytes]");						
						
						//previewDialog.setColumns(headers);
						previewDialog.showData(Dictionary.currentTemplate);
						previewDialog.setVisible(true);
					} catch (Exception e) {
						e.printStackTrace();
					}			
				}
			}
		};
		
		Thread thread = new Thread(openTask);
		thread.start();

	}
}
